<template>
  <div class="sub-filter" v-if="filterData && !filterLoading">
    <div class="subfilter-item">
      <div class="head">品牌:</div>
      <div class="body">
        <router-link
          to="#"
          :class="{ active: filterData.selectedBrand === brand.id }"
          v-for="brand in filterData.brands"
          :key="brand.id"
          >{{ brand.name }}</router-link
        >
      </div>
    </div>
    <div
      class="subfilter-item"
      v-for="p in filterData.saleProperties"
      :key="p.id"
    >
      <div class="head">{{ p.name }}:</div>
      <div class="body">
        <router-link
          class="line-ellipsis"
          :class="{ active: p.selectedProp === attr.id }"
          to="#"
          v-for="attr in p.properties"
          :key="attr.id"
          >{{ attr.name }}</router-link
        >
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { watch, ref } from 'vue'
import { subCategoryFilterAPI } from '@/api/category'
defineOptions({
  name: 'SubFilter'
})

/** 二级类目筛选条件 */
const filterData = ref()
/** 加载状态 */
const filterLoading = ref(false)

/** 获取路由信息对象 */
const route = useRoute()

/** 定义获取二级分类筛选条件 */
const getsubCategoryFilter = (id: string): void => {
  /** 开启加载状态 */
  filterLoading.value = true
  /** 调用接口 */
  subCategoryFilterAPI(id)
    .then((res) => {
      console.log(res)
      // 品牌全部
      res.selectedBrand = null
      res.brands.unshift({ id: null, name: '全部' })
      // 销售属性全部
      res.saleProperties.forEach((p) => {
        p.selectedProp = null
        p.properties.unshift({ id: null, name: '全部' })
      })
      /** 拿到后端响应的数据 */
      filterData.value = res
      /** 关闭加载状态 */
      filterLoading.value = false
    })
    .catch((err) => {
      console.log(err.message)
    })
}

/** 当进入该页面的时候就获取路由的路径参数发起请求 */
watch(
  () => route.params.id,
  (newValue) => {
    // 当你从二级分类去顶级分类也会拿到ID，不能去加载数据因为它不是二级分类的ID
    if (newValue && route.path === `/category/sub/${newValue as string}`) {
      getsubCategoryFilter(newValue as string)
    }
  },
  {
    immediate: true // 立即执行一次，不等数据变化后在执行
  }
)
</script>

<style lang="scss" scoped>
.subfilter {
  &-item {
    display: flex;
    padding: 25px;
    background: {
      color: $basic-white;
    }

    .head {
      width: 80px;
      color: #999;
      font-size: 14px;
    }

    .body {
      display: flex;
      flex-wrap: wrap;
      flex: 1;

      a {
        margin-right: 36px;
        max-width: 112px;
        height: 40px;
        font-size: 14px;

        &:hover,
        &.active {
          color: $xtx-color;
        }
      }
    }
  }
}
</style>
